<template>
  <div class="user">
    <el-select
      placeholder="请选择公司"
      @change="selectChanged"
      v-model="companyName"
      filterable
    >
      <el-option
        v-for="item in companyList"
        :label="item.name"
        :value="item.id"
        :key="item.id"
      ></el-option>
    </el-select>
    <el-dropdown @command="handleCommand">
      <div class="el-dropdown-link">
        {{ userInfo.userName }}
        <i class="el-icon-d-caret el-icon--right"></i>
      </div>
      <el-dropdown-menu slot="dropdown" size="mini">
        <el-dropdown-item command="clear">
          <i class="el-icon-delete"></i>退出登陆
        </el-dropdown-item>
        <el-dropdown-item command="setting">
          <i class="el-icon-setting"></i>个人设置
        </el-dropdown-item>
        <!-- <el-dropdown-item command="logout" divided>
          <i class="el-icon-switch-button"></i>退出登录
        </el-dropdown-item> -->
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>
<script>
import { loginOut, companySel, changeGroup, joinGroup } from "../utils/api";
export default {
  name: "User",
  inject: ["handlergetWarningListSimple"],

  data() {
    return {
      userInfo: {},
      errImg: 'this.src="' + require("../assets/images/user.png") + '"',
      fullscreenLoading: false,
      companyList: [],
      companyName: ""
    };
  },
  created() {
    this.userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));
    // this.$store.commit("CHANGE_VENUE", "");
    this.companyName = JSON.parse(
      window.sessionStorage.getItem("userInfo")
    ).companyId;
    this.getcompanySel();
    this.handlerShua();
  },

  methods: {
    handleCommand(command) {
      if (command === "clear") {
        const loading = this.$loading({
          lock: true,
          text: "清理中,请勿关闭!",
          background: "rgba(0, 0, 0, 0.5)"
        });
        setTimeout(() => {
          // this.$store.dispatch("clear").then(res => {
          loading.close();
          this.$notify({
            title: "清理完成",
            message: "请重新登录!",
            type: "success"
          });

          this.postRequest(loginOut).then(res => {
            // this.clearAllCookie();
            // window.sessionStorage.clear();
            window.sessionStorage.removeItem("clientId");
            window.sessionStorage.removeItem("companyId");
            window.sessionStorage.removeItem("logoimg");

            this.$router.push("/Login");
          });
          // });
        }, 1000);
      }
      if (command === "setting") {
        this.$router.push("/UserSetting");
      }
    },
    //删除所有的cookie
    clearAllCookie() {
      const keys = document.cookie.match(/[^ =;]+(?=\=)/g);
      if (keys) {
        for (let i = keys.length; i--; )
          document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
      }
    },
    // 获取公司列表
    getcompanySel() {
      this.postRequest(companySel).then(res => {
        if (res.code == 200) {
          this.companyList = res.data;

          this.companyName = window.sessionStorage.getItem("companyId")
            ? Number(window.sessionStorage.getItem("companyId"))
            : JSON.parse(window.sessionStorage.getItem("userInfo")).companyId;
          // this.companyName = window.sessionStorage.getItem("companyId");
          // console.log();
          // this.selectChanged(this.companyName);
          this.$store.commit("CHANGE_VENUE", this.companyName);
        }
      });
    },
    // 选中公司触发的函数
    selectChanged(val) {
      window.sessionStorage.setItem("companyId", this.companyName);
      this.companyList.map(item => {
        if (item.id == this.companyName) {
          window.sessionStorage.setItem("logoimg", item.logo);
        }
      });
      this.$store.commit("CHANGE_VENUE", this.companyName);
      this.postRequest(changeGroup, {
        client_id: window.sessionStorage.getItem("clientId")
      }).then(res => {});
      // this.handlergetWarningListSimple();
    },
    handlerShua() {
      console.log("刷新了");
      this.websocketTest();
    },
    websocketTest() {
      //初始化websocket
      // var url="ws://123.207.89.57:8282";
      // var url = "ws://47.99.74.117:8002";
      var url = "wss://tcp.wadd.vip/wss";

      this.websocket = new WebSocket(url);
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      // this.websocket.onclose = this.websocketclose;
    },
    websocketonopen() {
      window.console.log("连接成功");
      if (this.websocket.readyState == 1) {
        var data = {
          type: "login",
          device_id: "socketGroup" + window.sessionStorage.getItem("userId") + 2
        };
        var arr = JSON.stringify(data);
        this.websocket.send(arr);
      }

      // this.heatBeat();
    }, //连接成功
    websocketonerror() {
      window.console.log("连接失败");
    }, //连接失败
    websocketclose() {
      window.console.log("断开连接");
    },
    websocketonmessage(data) {
      // console.log(data);

      if (JSON.parse(data["data"])["type"] == "login") {
        const aa = JSON.parse(data["data"])["client_id"];
        window.sessionStorage.setItem("clientId", aa);

        var data1 = {
          type: "ping"
        };
        var arr1 = JSON.stringify(data1);
        setInterval(() => {
          this.websocketsend(arr1);
        }, 60000);
        //调接口
        this.postRequest(joinGroup, {
          client_id: JSON.parse(data["data"])["client_id"]
        }).then(res => {});
      }

      if (JSON.parse(data["data"])["type"] == "report") {
        //调接口
        this.handlergetWarningListSimple();
      }

      if (JSON.parse(data["data"])["type"] == "pong") {
        if (
          JSON.parse(data["data"])["client_id"] ==
          window.sessionStorage.getItem("clientId")
        ) {
        } else {
          this.websocketTest();
        }
      }

      //收到消息会刷新心跳检测，如果一直收到消息，就推迟心跳发送
      // this.heatBeat();
    }, //数据接收
    websocketsend(data) {
      console.log(data);
      // console.log(data);
      // this.websocket.send(JSON.stringify(data));
      this.websocket.send(data);
    },
    reconnect() {
      // if(this.lockReconnect){       //这里很关键，因为连接失败之后之后会相继触发 连接关闭，不然会连接上两个 WebSocket
      //     return
      // }
      // this.lockReconnect = true;
      // this.reconnectData && clearTimeout(this.reconnectData);
      // this.reconnectData = setTimeout(()=>{
      //     this.initWebSocket();
      //     this.lockReconnect = false;
      // },5000)
    },
    heatBeat() {
      // this.timeoutObj && clearTimeout(this.timeoutObj);
      // this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      // this.timeoutObj = setTimeout(()=>{
      //     this.websocketsend({type:'心跳检测'})   //根据后台要求发送
      //     this.serverTimeoutObj = setTimeout(()=> {
      //         this.websock.close();       //如果  5秒之后我们没有收到 后台返回的心跳检测数据 断开socket，断开后会启动重连机制
      //     }, 5000);
      // }, this.timeout)
    },
    destroyed() {
      // this.lockReconnect = true;
      // this.websock.close()                   //离开路由之后断开websocket连接
      // clearTimeout(this.reconnectData);      //离开清除 timeout
      // clearTimeout(this.timeoutObj);         //离开清除 timeout
      // clearTimeout(this.serverTimeoutObj);   //离开清除 timeout
    }
  }
};
</script>

<style scoped>
.user {
  padding-left: 15px;
  box-sizing: border-box;
  /* border-left: 1px solid #EAEDF3; */
}
.el-dropdown-link {
  color: #3e3f42;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  border: 1px solid #dcdfe6;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  padding: 0 15px;
  cursor: pointer;
}

.el-icon-caret-bottom {
  color: rgba(62, 63, 66, 1);
  font-size: 16px;
}
</style>
